import BasePlugin from './BasePlugin';

/**
 * 导入插件 - 处理画布导入功能
 */
export default class ImportPlugin extends BasePlugin {
    constructor() {
        super();
        this.supportedImageTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/svg+xml'
        ];
        this.maxImageSize = 10 * 1024 * 1024; // 10MB
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
        this._setupEventListeners();
    }

    /**
     * 从文件导入
     */
    importFromFile(file, options = {}) {
        if (!this.isEnabled() || !this.canvas || !file) return;

        const fileType = file.type.toLowerCase();

        // 检查文件类型
        if (fileType.includes('image')) {
            this._importImage(file, options);
        } else if (fileType === 'application/json') {
            this._importJSON(file, options);
        } else if (fileType === 'text/svg+xml') {
            this._importSVG(file, options);
        } else {
            this._emitImportEvent('error', {
                error: 'Unsupported file type',
                file
            });
        }
    }

    /**
     * 从 URL 导入
     */
    importFromURL(url, options = {}) {
        if (!this.isEnabled() || !this.canvas || !url) return;

        // 检查 URL 类型
        if (this._isImageURL(url)) {
            this._importImageFromURL(url, options);
        } else if (url.endsWith('.json')) {
            this._importJSONFromURL(url, options);
        } else if (url.endsWith('.svg')) {
            this._importSVGFromURL(url, options);
        } else {
            this._emitImportEvent('error', {
                error: 'Unsupported URL type',
                url
            });
        }
    }

    /**
     * 从剪贴板导入
     */
    importFromClipboard(options = {}) {
        if (!this.isEnabled() || !this.canvas) return;

        navigator.clipboard.read().then(items => {
            items.forEach(item => {
                // 检查是否包含图片
                if (item.types.includes('image/png')) {
                    item.getType('image/png').then(blob => {
                        this._importImage(blob, options);
                    });
                }
            });
        }).catch(error => {
            this._emitImportEvent('error', {
                error: 'Failed to read clipboard',
                details: error
            });
        });
    }

    /**
     * 导入图片
     */
    _importImage(file, options = {}) {
        // 检查文件大小
        if (file.size > this.maxImageSize) {
            this._emitImportEvent('error', {
                error: 'Image size exceeds limit',
                file
            });
            return;
        }

        // 检查文件类型
        if (!this.supportedImageTypes.includes(file.type)) {
            this._emitImportEvent('error', {
                error: 'Unsupported image type',
                file
            });
            return;
        }

        const reader = new FileReader();
        reader.onload = (e) => {
            fabric.Image.fromURL(e.target.result, (img) => {
                this._processImportedImage(img, options);
            });
        };
        reader.readAsDataURL(file);
    }

    /**
     * 从 URL 导入图片
     */
    _importImageFromURL(url, options = {}) {
        fabric.Image.fromURL(url, (img) => {
            this._processImportedImage(img, options);
        }, {
            crossOrigin: 'anonymous'
        });
    }

    /**
     * 处理导入的图片
     */
    _processImportedImage(img, options = {}) {
        // 调整图片大小
        if (options.maxWidth || options.maxHeight) {
            const scale = Math.min(
                options.maxWidth ? options.maxWidth / img.width : 1,
                options.maxHeight ? options.maxHeight / img.height : 1
            );
            img.scale(scale);
        }

        // 设置图片位置
        if (options.left !== undefined && options.top !== undefined) {
            img.set({
                left: options.left,
                top: options.top
            });
        } else {
            // 默认居中
            this.canvas.centerObject(img);
        }

        // 添加到画布
        this.canvas.add(img);
        if (options.select) {
            this.canvas.setActiveObject(img);
        }
        this.canvas.renderAll();

        this._emitImportEvent('image', {
            image: img,
            options
        });
    }

    /**
     * 导入 JSON
     */
    _importJSON(file, options = {}) {
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const json = JSON.parse(e.target.result);
                this._loadJSONData(json, options);
            } catch (error) {
                this._emitImportEvent('error', {
                    error: 'Invalid JSON file',
                    details: error
                });
            }
        };
        reader.readAsText(file);
    }

    /**
     * 从 URL 导入 JSON
     */
    _importJSONFromURL(url, options = {}) {
        fetch(url)
            .then(response => response.json())
            .then(json => {
                this._loadJSONData(json, options);
            })
            .catch(error => {
                this._emitImportEvent('error', {
                    error: 'Failed to load JSON from URL',
                    details: error
                });
            });
    }

    /**
     * 加载 JSON 数据
     */
    _loadJSONData(json, options = {}) {
        if (options.clear) {
            this.canvas.clear();
        }

        this.canvas.loadFromJSON(json, () => {
            this.canvas.renderAll();
            this._emitImportEvent('json', {
                json,
                options
            });
        });
    }

    /**
     * 导入 SVG
     */
    _importSVG(file, options = {}) {
        const reader = new FileReader();
        reader.onload = (e) => {
            fabric.loadSVGFromString(e.target.result, (objects, svgOptions) => {
                this._processSVGObjects(objects, svgOptions, options);
            });
        };
        reader.readAsText(file);
    }

    /**
     * 从 URL 导入 SVG
     */
    _importSVGFromURL(url, options = {}) {
        fabric.loadSVGFromURL(url, (objects, svgOptions) => {
            this._processSVGObjects(objects, svgOptions, options);
        });
    }

    /**
     * 处理 SVG 对象
     */
    _processSVGObjects(objects, svgOptions, options = {}) {
        if (!objects || objects.length === 0) return;

        // 创建 SVG 组
        const svg = fabric.util.groupSVGElements(objects, svgOptions);

        // 调整大小
        if (options.maxWidth || options.maxHeight) {
            const scale = Math.min(
                options.maxWidth ? options.maxWidth / svg.width : 1,
                options.maxHeight ? options.maxHeight / svg.height : 1
            );
            svg.scale(scale);
        }

        // 设置位置
        if (options.left !== undefined && options.top !== undefined) {
            svg.set({
                left: options.left,
                top: options.top
            });
        } else {
            // 默认居中
            this.canvas.centerObject(svg);
        }

        // 添加到画布
        this.canvas.add(svg);
        if (options.select) {
            this.canvas.setActiveObject(svg);
        }
        this.canvas.renderAll();

        this._emitImportEvent('svg', {
            svg,
            options
        });
    }

    /**
     * 检查是否为图片 URL
     */
    _isImageURL(url) {
        return /\.(jpg|jpeg|png|gif|bmp)$/i.test(url);
    }

    /**
     * 设置事件监听
     */
    _setupEventListeners() {
        if (!this.canvas) return;

        // 监听拖放事件
        this.canvas.wrapperEl.addEventListener('dragover', (e) => {
            e.preventDefault();
            e.stopPropagation();
        });

        this.canvas.wrapperEl.addEventListener('drop', (e) => {
            e.preventDefault();
            e.stopPropagation();

            const files = e.dataTransfer.files;
            if (files.length > 0) {
                this.importFromFile(files[0]);
            }
        });

        // 监听粘贴事件
        document.addEventListener('paste', (e) => {
            if (!this.isEnabled()) return;

            const items = e.clipboardData.items;
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.indexOf('image') !== -1) {
                    const file = items[i].getAsFile();
                    this.importFromFile(file);
                    break;
                }
            }
        });
    }

    /**
     * 发送导入事件
     */
    _emitImportEvent(type, data = null) {
        this.editor.emit('import:' + type, {
            type,
            data
        });
    }

    /**
     * 销毁插件
     */
    destroy() {
        if (this.canvas) {
            this.canvas.wrapperEl.removeEventListener('dragover', this._handleDragOver);
            this.canvas.wrapperEl.removeEventListener('drop', this._handleDrop);
            document.removeEventListener('paste', this._handlePaste);
        }
        super.destroy();
    }
} 